package com.yunshipei.core.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class RootCheck {

    public boolean isDeviceRooted() {
        return checkRootMethod1() || checkRootMethod2() || checkRootMethod3();
    }

    private boolean checkRootMethod1() {
        String buildTags = android.os.Build.TAGS;
        return buildTags != null && buildTags.contains("test-keys");
    }

    private boolean checkRootMethod2() {
        try {
            File file = new File("/system/app/Superuser.apk");
            if (file.exists()) {
                return true;
            }
        } catch (Exception ignored) {
        }
        return false;
    }

    private boolean checkRootMethod3() {
        return getDemo(SHELL_CMD.check_su_binary) != null;
    }

    private ArrayList<String> getDemo(SHELL_CMD shellCmd) {
        ArrayList<String> fullResponse = new ArrayList<>();

        try {
            Process localProcess = Runtime.getRuntime().exec(shellCmd.command);
            BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                fullResponse.add(line);
            }
        } catch (Exception e) {
            return null;
        }
        return fullResponse;
    }

    private enum SHELL_CMD {
        check_su_binary(new String[]{"/system/xbin/which", "su"}),;

        String[] command;

        SHELL_CMD(String[] command) {
            this.command = command;
        }
    }
}
